package me.tuyou.jvm.reference;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;

/**
 * 虚引用测试
 * 虚引用的get直接返回null
 * 因为虚引用在gc后会放入ReferenceQueue，可用于跟踪gc回收
 * 放入队列的是引用，值已经被gc回收
 * @Author tuyou_cd
 * @Date 2020/7/22 15:00
 */
public class PhantomReferenceTest {

    public static void main(String[] args) throws InterruptedException {
        ReferenceQueue queue = new ReferenceQueue<>();

//        MyObject obj = new MyObject("1");
        String obj = new String("23123123");
        PhantomReference reference = new PhantomReference<>(obj, queue);

        System.out.println("引用值：" + reference.get()); //null

        System.out.println(reference.isEnqueued()); //false
        System.out.println(queue.poll() == reference); //false

        System.gc();
        Thread.sleep(1000); //延时1秒，等待gc完毕

        System.out.println(reference.isEnqueued()); //true
        System.out.println(queue.poll() == reference); //true
    }
}
